package com.electric.flinkcep.service;

import com.electric.flinkcep.config.ConfigManager;
import com.electric.flinkcep.model.Alert;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;

/**
 * HTTP客户端服务
 * 负责向后端发送POST请求
 */
public class HttpClientService implements Serializable {
    
    private static final Logger logger = LoggerFactory.getLogger(HttpClientService.class);
    private final ConfigManager configManager;
    private final ObjectMapper objectMapper;
    private final RequestConfig requestConfig;
    
    public HttpClientService() {
        this.configManager = ConfigManager.getInstance();
        this.objectMapper = new ObjectMapper();
        
        // 配置HTTP请求超时
        this.requestConfig = RequestConfig.custom()
                .setConnectTimeout(configManager.getHttpConnectionTimeout())
                .setSocketTimeout(configManager.getHttpSocketTimeout())
                .setConnectionRequestTimeout(configManager.getHttpConnectionTimeout())
                .build();
    }
    
    /**
     * 发送告警到后端
     * @param alert 告警对象
     * @return 是否发送成功
     */
    public boolean sendAlert(Alert alert) {
        if (alert == null) {
            logger.warn("告警对象为空，跳过发送");
            return false;
        }
        
        try {
            String jsonPayload = objectMapper.writeValueAsString(alert);
            return sendPostRequest(configManager.getHttpBackendUrl(), jsonPayload);
        } catch (Exception e) {
            logger.error("序列化告警对象失败: {}", alert, e);
            return false;
        }
    }
    
    /**
     * 发送POST请求
     * @param url 目标URL
     * @param jsonPayload JSON负载
     * @return 是否发送成功
     */
    private boolean sendPostRequest(String url, String jsonPayload) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            
            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("User-Agent", "FlinkCEP/1.0.0");
            
            // 设置请求体
            StringEntity entity = new StringEntity(jsonPayload, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);
            
            logger.debug("发送POST请求到: {}, 负载: {}", url, jsonPayload);
            
            // 执行请求
            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            
            // 读取响应内容
            HttpEntity responseEntity = response.getEntity();
            String responseBody = "";
            if (responseEntity != null) {
                responseBody = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            }
            
            // 判断请求是否成功
            if (statusCode >= 200 && statusCode < 300) {
                logger.info("POST请求发送成功, 状态码: {}, 响应: {}", statusCode, responseBody);
                return true;
            } else {
                logger.warn("POST请求失败, 状态码: {}, 响应: {}", statusCode, responseBody);
                return false;
            }
            
        } catch (IOException e) {
            logger.error("发送POST请求失败, URL: {}, 负载: {}", url, jsonPayload, e);
            return false;
        }
    }
    
    /**
     * 发送自定义JSON数据
     * @param jsonData JSON数据
     * @return 是否发送成功
     */
    public boolean sendJsonData(String jsonData) {
        if (jsonData == null || jsonData.trim().isEmpty()) {
            logger.warn("JSON数据为空，跳过发送");
            return false;
        }
        
        return sendPostRequest(configManager.getHttpBackendUrl(), jsonData);
    }
    
    /**
     * 测试连接
     * @return 是否连接成功
     */
    public boolean testConnection() {
        try {
            String testPayload = "{\"test\": true, \"timestamp\": " + System.currentTimeMillis() + "}";
            return sendPostRequest(configManager.getHttpBackendUrl(), testPayload);
        } catch (Exception e) {
            logger.error("测试连接失败", e);
            return false;
        }
    }
}